// user.js

var user = require('../../model').user;
var logger = require('log4js').getLogger('user.index.js');

exports.add = function add(req, res) {
    if (!req.query.name || !req.query.age) {
        return res.send('params error!');
    }
    var test = { id: Date.now(), name: req.query.name, age: req.query.age }
        , con = { "name": req.query.name };

    user.findOne(con, (err, rel) => {
        if (err) return res.send(err);
        if (rel) {
            user.update(con, test, (err, rel) => {
                if (err) return res.send(err);
                console.log('修改用户成功');
                // res.send({ msg: '此用户已存在，更新信息！', new: { name: test.name, age: test.age } });
                res.redirect(301, 'http://localhost:3000/user');
            });
        }
        else {
            rel = new user(test);
            rel.save((err, rel) => {
                if (err) return res.send(err);
                // res.send({ msg: '新增用户成功', info: { name: test.name, age: test.age } });
                console.log('新增用户成功');
                res.redirect(301, 'http://localhost:3000/user');
            });
        }
    });
};

exports.index = function index(req, res) {
    var record = 10;
    if (req.query.record) {
        record = Number(req.query.record);
    }
    user.find({}).select('-_id -id').sort('-age').limit(record).exec((err, rel) => {
        if (err) return res.send(err);
        res.json({ rel });
    });
};

exports.about = function about(req, res) {
    res.send('about user');
};
